// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    baseURL:wx.baseURL,
    news:[],
    newsIndex:0,
    newsTimer:0,
    newsItems:'transform: translate(0rpx, 0rpx)',
    // 获取分类栏
    categorys:[],
    // 获取推荐列表
    recommends:[],
    allRecommend: [],
    pageIndex: 1, //默认为第一页
    pageSize: 1, //每一页有两条数据
    pageNum: 1,
    total: 0,
    loading:'loading...',
    // 获取首页顶部轮播
    banners:[],
  },
  // 新闻
  getNews() {
    return new Promise((resolve,reject) => {
      wx.get('/index/news').then((res) => {
        this.setData({
          news:res
        })
        this.changeNewIndex() //触发新闻轮播
        resolve()
      })
    })
  },

  // 新闻轮播
  changeNewIndex() {
    if (this.data.newsTimer) {
      clearInterval(this.data.newsTimer)
      this.data.newsTimer = 0
    }
    this.data.newsTimer = setInterval(() => {
      let newsIndex = this.data.newsIndex
      newsIndex++
      //if (newsIndex == this.data.news.length) newsIndex = 0 //最后一张图切换到第一张图
      //console.log('这是第几张', newsIndex)
      this.setData({
        newsIndex,
        newItems:'transform: translate(0rpx, -' + newsIndex * 80 + 'rpx);transition: transform 0.3s;'
      })
      if(this.data.newsIndex == this.data.news.length){
        setTimeout(()=>{
          this.setData({
            newsIndex:0,
            newItems:'transform: translate(0rpx, 0rpx);'
          })
        },500)
      }
    }, 3000)
  },
  //下拉刷新
  onPullDownRefresh() {
    this.data.pageNum = 1
    this.data.lists = []
    this.getList()
  },
  // 轮播图
  getBanners() {
    return new Promise((resolve,reject) => {
      wx.get('/index/banners').then(res => {
        this.setData({
          banners:res
        })
        resolve()
      })
    })
  },
  // 轮播图跳转事件
  swiperClick() {
    let path = this.data.banners.path
    wx.switchTab({
      url: this.path,
    })

  },
  // 获取分类
  getCategorys() {
    return new Promise((resolve,reject) => {

      wx.get('/index/categorys').then((res) => {
        this.setData({
          categorys:res
        })
        resolve()
      })
    })
    
  },
  onReachBottom(){
    if(this.data.total > this.data.lists.length){
      this.data.pageNum ++
      this.getRecomend()
    }
    
  },
  getRecomends(){
    return new Promise((resolve,reject) => {
      this.setData({loading:'数据加载中...'})
      wx.get('/index/recommends',{
        pageNum:this.data.pageNum
      }).then(res => {
        console.log(res)
        this.setData({
          loading:'小主，已经到底了哦~',
          recommends:this.data.recommends.concat(res.rows),
          total:res.total
        })
        resolve()
      })
    })
  },
  getList(){
    Promise.all([this.getNews(),this.getBanners(),this.getCategorys(),this.getRecomends()]).then(() => {
      console.log('所有数据加载完成')
    }).catch(e => {
      console.log(e)
    })
  },
  onLoad() {
    this.getList()
  }
})
